import { io, Socket } from 'socket.io-client'
import { SocketUrl, SocketPort } from '../config.json'

interface SocketReturn {
    socket: Socket
    status: Ref<boolean>
    connect: () => void
    disconnect: () => void
    emit: (event: string, data?: any) => void
    on: (event: string, callback: (data: any) => void) => void
    off: (event: string) => void
}

const SCOKET_URL = `${SocketUrl}:${SocketPort}`

export const useSocket = (): SocketReturn => {
    const socket = io(SCOKET_URL, { autoConnect: false })
    const status = ref(false)

    const connect = () => {
        if (status.value) return
        socket.connect()
    }

    const disconnect = () => {
        if (!status.value) return
        socket.disconnect()
    }

    socket.on('connect', () => (status.value = true))
    socket.on('disconnect', () => (status.value = false))

    return {
        socket,
        status,
        connect,
        disconnect,
        emit: (event, data) => socket.emit(event, data),
        on: (event, callback) => socket.on(event, callback),
        off: (event) => socket.off(event)
    }
}